const BEIJING_OFFSET_MS = 8 * 60 * 60 * 1000

export const BEIJING_TIMEZONE = 'Asia/Shanghai'

const HOUR_IN_MS = 60 * 60 * 1000

const shiftToBeijingTimestamp = (date: Date): number => date.getTime() + BEIJING_OFFSET_MS

const shiftFromBeijingTimestamp = (timestamp: number): Date => new Date(timestamp - BEIJING_OFFSET_MS)

export const getBeijingStartOfDay = (date: Date): Date => {
  const beijingTimestamp = shiftToBeijingTimestamp(date)
  const beijingDate = new Date(beijingTimestamp)
  beijingDate.setUTCHours(0, 0, 0, 0)
  return shiftFromBeijingTimestamp(beijingDate.getTime())
}

export const addBeijingHours = (date: Date, hours: number): Date => {
  return new Date(date.getTime() + hours * HOUR_IN_MS)
}

export const formatBeijingTime = (date: Date): string => {
  return date.toLocaleString('zh-CN', { timeZone: BEIJING_TIMEZONE })
}

export const isSameBeijingDay = (a?: Date | null, b?: Date | null): boolean => {
  if (!a || !b) {
    return false
  }
  return getBeijingStartOfDay(a).getTime() === getBeijingStartOfDay(b).getTime()
}

export const getBeijingNow = (): Date => {
  return new Date()
}

